import { Router } from 'express';
import { body, validationResult } from 'express-validator';
import { authenticateToken, authorizeRole } from '../middleware/auth';
import { validateRequest } from '../middleware/validation';
import { config } from '../config';
import { prisma } from '../lib/prisma';
import os from 'os';

const router = Router();

// 获取系统信息
const getSystemInfo = () => {
  const memUsage = process.memoryUsage();
  const cpuUsage = process.cpuUsage();
  
  return {
    version: 'v1.0.0',
    nodeVersion: process.version,
    platform: process.platform,
    arch: process.arch,
    uptime: process.uptime(),
    memory: {
      used: Math.round(memUsage.heapUsed / 1024 / 1024),
      total: Math.round(memUsage.heapTotal / 1024 / 1024),
      external: Math.round(memUsage.external / 1024 / 1024),
      rss: Math.round(memUsage.rss / 1024 / 1024)
    },
    cpu: {
      user: Math.round(cpuUsage.user / 1000),
      system: Math.round(cpuUsage.system / 1000)
    },
    loadAverage: os.loadavg(),
    freeMemory: Math.round(os.freemem() / 1024 / 1024),
    totalMemory: Math.round(os.totalmem() / 1024 / 1024)
  };
};

// 获取数据库信息
const getDatabaseInfo = async () => {
  try {
    const result = await prisma.$queryRaw`SELECT version() as version`;
    const version = (result as any)[0]?.version || 'Unknown';
    
    return {
      type: 'PostgreSQL',
      version: version.split(' ')[1] || 'Unknown',
      tables: 0,
      stats: []
    };
  } catch (error: any) {
    return {
      type: 'Unknown',
      version: 'Unknown',
      error: error.message
    };
  }
};

// 获取所有设置
router.get('/', 
  authenticateToken,
  authorizeRole(['ADMIN']),
  async (req, res, next) => {
    try {
      const [systemInfo, databaseInfo] = await Promise.all([
        Promise.resolve(getSystemInfo()),
        getDatabaseInfo()
      ]);

      const settings = {
        general: {
          siteName: config.BASE_URL.includes('localhost') ? '知识库管理系统' : '知识库管理系统',
          siteDescription: '企业级知识库管理系统',
          siteUrl: config.BASE_URL,
          adminEmail: config.SMTP_FROM,
          postsPerPage: config.DEFAULT_PAGE_SIZE,
          allowComments: true,
          allowRegistration: true,
          requireEmailVerification: false
        },
        security: {
          passwordMinLength: config.PASSWORD_MIN_LENGTH,
          passwordComplexity: 'medium', // 低/中/高
          passwordExpiryDays: 90,
          loginFailLockCount: 5,
          sessionTimeout: 30, // 分钟
          maxConcurrentLogins: 3,
          rememberLogin: true
        },
        notifications: {
          smtp: {
            host: config.SMTP_HOST,
            port: config.SMTP_PORT,
            user: config.SMTP_USER,
            password: config.SMTP_PASS,
            from: config.SMTP_FROM,
            enableTLS: config.SMTP_PORT === 587
          },
          events: {
            userRegistration: { email: true, system: true },
            newArticle: { email: false, system: true },
            commentReply: { email: false, system: true },
            systemMaintenance: { email: true, system: true },
            securityWarning: { email: true, system: true }
          }
        },
        database: {
          type: 'PostgreSQL',
          host: config.DATABASE_URL.split('@')[1]?.split('/')[0]?.split(':')[0] || 'localhost',
          port: config.DATABASE_URL.includes(':5432') ? 5432 : 5432,
          name: config.DATABASE_URL.split('/').pop()?.split('?')[0] || 'zhishiku',
          autoBackup: config.ENABLE_AUTO_BACKUP,
          backupFrequency: 'daily', // hourly/daily/weekly
          backupRetentionDays: config.BACKUP_RETENTION_DAYS
        },
        system: {
          ...systemInfo,
          database: databaseInfo,
          logs: {
            level: config.LOG_LEVEL,
            retentionDays: 90,
            enableAccessLog: true
          }
        }
      };

      res.json({
        code: 200,
        message: '获取系统设置成功',
        data: { settings }
      });
    } catch (error) {
      next(error);
    }
  }
);

// 更新设置
router.put('/', 
  authenticateToken,
  authorizeRole(['ADMIN']),
  [
    // 基本设置验证
    body('general.siteName').optional().isLength({ min: 1, max: 100 }).withMessage('网站名称长度必须在1-100个字符之间'),
    body('general.siteDescription').optional().isLength({ max: 500 }).withMessage('网站描述长度不能超过500个字符'),
    body('general.siteUrl').optional().isURL().withMessage('请输入有效的网站地址'),
    body('general.adminEmail').optional().isEmail().withMessage('请输入有效的管理员邮箱'),
    body('general.postsPerPage').optional().isInt({ min: 5, max: 100 }).withMessage('每页显示文章数必须在5-100之间'),
    
    // 安全设置验证
    body('security.passwordMinLength').optional().isInt({ min: 6, max: 20 }).withMessage('最小密码长度必须在6-20之间'),
    body('security.passwordComplexity').optional().isIn(['low', 'medium', 'high']).withMessage('密码复杂度必须是低/中/高'),
    body('security.passwordExpiryDays').optional().isInt({ min: 0, max: 365 }).withMessage('密码过期天数必须在0-365之间'),
    body('security.loginFailLockCount').optional().isInt({ min: 3, max: 10 }).withMessage('登录失败锁定次数必须在3-10之间'),
    body('security.sessionTimeout').optional().isInt({ min: 5, max: 1440 }).withMessage('会话超时时间必须在5-1440分钟之间'),
    body('security.maxConcurrentLogins').optional().isInt({ min: 1, max: 10 }).withMessage('最大并发登录数必须在1-10之间'),
    
    // 通知设置验证
    body('notifications.smtp.host').optional().isString().withMessage('SMTP服务器地址不能为空'),
    body('notifications.smtp.port').optional().isInt({ min: 1, max: 65535 }).withMessage('SMTP端口必须在1-65535之间'),
    body('notifications.smtp.user').optional().isString().withMessage('SMTP用户名不能为空'),
    body('notifications.smtp.password').optional().isString().withMessage('SMTP密码不能为空'),
    body('notifications.smtp.from').optional().isEmail().withMessage('发件人邮箱格式无效'),
    
    // 数据库设置验证
    body('database.autoBackup').optional().isBoolean().withMessage('自动备份必须是布尔值'),
    body('database.backupFrequency').optional().isIn(['hourly', 'daily', 'weekly']).withMessage('备份频率必须是每小时/每天/每周'),
    body('database.backupRetentionDays').optional().isInt({ min: 1, max: 365 }).withMessage('备份保留天数必须在1-365之间'),
    
    // 系统设置验证
    body('system.logs.level').optional().isIn(['error', 'warn', 'info', 'debug']).withMessage('日志级别必须是错误/警告/信息/调试'),
    body('system.logs.retentionDays').optional().isInt({ min: 1, max: 365 }).withMessage('日志保留天数必须在1-365之间'),
    body('system.logs.enableAccessLog').optional().isBoolean().withMessage('启用访问日志必须是布尔值')
  ],
  validateRequest,
  async (req, res, next) => {
    try {
      const { general, security, notifications, database, system } = req.body;
      
      // 这里应该将设置保存到数据库或配置文件
      // 目前先返回成功响应，实际项目中需要实现配置持久化
      
      // 模拟保存操作
      console.log('保存系统设置:', {
        general,
        security,
        notifications,
        database,
        system
      });
      
      res.json({
        code: 200,
        message: '系统设置更新成功',
        data: {
          updatedAt: new Date().toISOString(),
          settings: {
            general,
            security,
            notifications,
            database,
            system
          }
        }
      });
    } catch (error) {
      next(error);
    }
  }
);

// 获取特定分类的设置
router.get('/:category', 
  authenticateToken,
  authorizeRole(['ADMIN']),
  async (req, res, next) => {
    try {
      const { category } = req.params;
      
      let settings = {};
      
      switch (category) {
        case 'general':
          settings = {
            siteName: config.BASE_URL.includes('localhost') ? '知识库管理系统' : '知识库管理系统',
            siteDescription: '企业级知识库管理系统',
            siteUrl: config.BASE_URL,
            adminEmail: config.SMTP_FROM,
            postsPerPage: config.DEFAULT_PAGE_SIZE,
            allowComments: true,
            allowRegistration: true,
            requireEmailVerification: false
          };
          break;
          
        case 'security':
          settings = {
            passwordMinLength: config.PASSWORD_MIN_LENGTH,
            passwordComplexity: 'medium',
            passwordExpiryDays: 90,
            loginFailLockCount: 5,
            sessionTimeout: 30,
            maxConcurrentLogins: 3,
            rememberLogin: true
          };
          break;
          
        case 'notifications':
          settings = {
            smtp: {
              host: config.SMTP_HOST,
              port: config.SMTP_PORT,
              user: config.SMTP_USER,
              password: config.SMTP_PASS,
              from: config.SMTP_FROM,
              enableTLS: config.SMTP_PORT === 587
            },
            events: {
              userRegistration: { email: true, system: true },
              newArticle: { email: false, system: true },
              commentReply: { email: false, system: true },
              systemMaintenance: { email: true, system: true },
              securityWarning: { email: true, system: true }
            }
          };
          break;
          
        case 'database':
          const databaseInfo = await getDatabaseInfo();
          settings = {
            type: 'PostgreSQL',
            host: config.DATABASE_URL.split('@')[1]?.split('/')[0]?.split(':')[0] || 'localhost',
            port: config.DATABASE_URL.includes(':5432') ? 5432 : 5432,
            name: config.DATABASE_URL.split('/').pop()?.split('?')[0] || 'zhishiku',
            autoBackup: config.ENABLE_AUTO_BACKUP,
            backupFrequency: 'daily',
            backupRetentionDays: config.BACKUP_RETENTION_DAYS,
            info: databaseInfo
          };
          break;
          
        case 'system':
          const systemInfo = getSystemInfo();
          const dbInfo = await getDatabaseInfo();
          settings = {
            ...systemInfo,
            database: dbInfo,
            logs: {
              level: config.LOG_LEVEL,
              retentionDays: 90,
              enableAccessLog: true
            }
          };
          break;
          
        default:
          return res.status(400).json({
            code: 400,
            message: '无效的设置分类',
            error: `不支持的设置分类: ${category}`
          });
      }
      
      res.json({
        code: 200,
        message: `获取${category}设置成功`,
        data: { settings }
      });
    } catch (error) {
      next(error);
    }
  }
);

export { router as settingsRoutes };
